package com.gewu.bluetoothflow.ui

import android.app.ProgressDialog
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.eciot.ble_demo_kotlin.ECBLE
import com.gewu.bluetoothflow.bean.BleDeviceInfo
import com.gewu.bluetoothflow.tools.PreferencesManager
import com.google.gson.Gson
import pub.devrel.easypermissions.EasyPermissions
import java.text.SimpleDateFormat
import java.util.*

/**
 *  16024120041000
 * 型号定义如下表：
 * 红外人员计数器单机版	160
 * 红外人员计数器WiFi版	161
 * 红外人员计数器Cat.1版	163
 * 红外人员计数器Cat.M版	165
 * 红外人员计数器lorawan版	166
 * PIR人员计数器(bt+cat1)	150
 * 磁力车辆计数器(bt+cat1) 911
 */
 open class BaseActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks {
    val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
    val timeFormat = SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA)
     var prefsManager: PreferencesManager? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val height= getStatusBarHeight(this)
        Log.d("BaseActivity","====> height: $height")
        prefsManager = PreferencesManager(this)
        val lang = prefsManager!!.languages
        // switchLanguage(lang,false)
       // enableEdgeToEdge()

        var perms = arrayOf(
            android.Manifest.permission.ACCESS_FINE_LOCATION,
            android.Manifest.permission.ACCESS_COARSE_LOCATION,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE
        )
        if (!EasyPermissions.hasPermissions(this, *perms)) {
            // 没有权限，进行权限请求
            EasyPermissions.requestPermissions(this, "请打开应用的定位权限", 0xECB001, *perms)
            return
        }
        //安卓12或以上，还需要蓝牙连接附近设备的权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            perms = arrayOf(
                android.Manifest.permission.BLUETOOTH_SCAN,
                android.Manifest.permission.BLUETOOTH_ADVERTISE,
                android.Manifest.permission.BLUETOOTH_CONNECT
            )
            if (!EasyPermissions.hasPermissions(this, *perms)) {
                // 没有蓝牙权限，进行权限请求
                EasyPermissions.requestPermissions(
                    this,
                    "请打开应用的蓝牙权限，允许应用使用蓝牙连接附近的设备",
                    0xECB002,
                    *perms
                )
                return
            }
        }

//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
//            WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

//        getWindow().setFlags(
//            WindowManager.LayoutParams.FLAG_FULLSCREEN,
//            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

     fun getStatusBarHeight(context: Context): Int {
         var result = 0
         val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
         if (resourceId > 0) {
             result = context.resources.getDimensionPixelSize(resourceId)
         }
         return result
     }
    fun showToast(text: String) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
    }

     fun showAlert(title:String,content: String, callback: () -> Unit) {
        runOnUiThread {
            AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(content)
                .setPositiveButton("确定") { _, _ -> callback() }
                .setCancelable(false)
                .create().show()
        }
    }

     private fun switchLanguage(lange: String,setting:Boolean) {
         if (lange.isNullOrEmpty()) return

         var locale :Locale = Locale.SIMPLIFIED_CHINESE
         when(lange){
             Locale.ENGLISH.language -> locale = Locale.ENGLISH
             Locale.SIMPLIFIED_CHINESE.language -> locale = Locale.SIMPLIFIED_CHINESE
         }

         //设置应用语言类型
         val resources = resources
         val config: Configuration = resources.configuration
         val dm = resources.displayMetrics
         config.setLocale(locale)
         resources.updateConfiguration(config, dm)
         prefsManager!!.languages = locale.language.toString()

         if (setting) {
             recreate()
         }
     }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        Log.d("","onRequestPermissionsResult : $requestCode")
        if ((requestCode == 0xECB002 || requestCode == 0xECB001) && grantResults.size > 0){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Log.d("","onRequestPermissionsResult : $requestCode   -- OK")
            }
        }

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String?>) {
//        Log.e("onPermissionsGranted", "requestCode=$requestCode")
        ECBLE.onPermissionsGranted(this,requestCode,perms)
    }
    override fun onPermissionsDenied(requestCode: Int, perms: List<String?>) {
        //获取权限失败
//        Log.e("onPermissionsDenied", "requestCode=$requestCode")
//        for (perm in perms) {
//            Log.e("perm:", perm!!)
//        }
        ECBLE.onPermissionsDenied(requestCode,perms)
    }
}